package com.lmx.healthcode.common.base;

import android.content.Context;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author Leung
 * @date 2020/9/11 19:56
 */
public abstract class BaseAdapterRv<T> extends RecyclerView.Adapter {

    /**
     * 上下文
     */
    private Context context;

    /**
     * 数据源
     */
    private List<T> listData;

    public BaseAdapterRv(Context context, List<T> listData) {
        this.context = context;
        this.listData = listData;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return createViewHolder(context, parent, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        BaseHolderRv<T> baseHolderRv = (BaseHolderRv<T>) holder;
        T bean = getItem(position);
        baseHolderRv.refreshView(bean, position);
    }

    @Override
    public int getItemCount() {
        return listData != null ? listData.size() : 0;
    }

    /**
     * 创建ViewHolder
     *
     * @param context 上下文
     * @param parent 父容器
     * @param viewType 视图类型
     * @return ViewHolder
     */
    public abstract BaseHolderRv<T> createViewHolder(Context context, ViewGroup parent, int viewType);

    /**
     * 获取指定位置列表项的实体类
     * @param position 列表项位置
     * @return 实体类
     */
    public T getItem(int position) {
        return listData.get(position);
    }

    /**
     * 删除指定列表项
     * @param bean 要删除的实体类
     * @return 是否删除成功
     */
    public boolean removeItem(T bean) {
        boolean result = listData.remove(bean);
        notifyDataSetChanged();
        return result;
    }

    /**
     * 设置数据
     *
     * @param data 数据源
     */
    public void setData(List<T> data) {
        listData = data;
        notifyDataSetChanged();
    }

}
